class Solution {
    int[][] nextPostition = {{0,1}, {1,0}, {0, -1}, {-1, 0}};
    public int numIslands(char[][] grid) {
        int row = grid.length;
        int col = grid[0].length;
        int ret = 0;
        for(int i = 0; i < row; i++){
            for(int j = 0; j < col; j++){
                if(grid[i][j] == '1'){
                    ret++;
                    dfs(grid, row, col, i,j);
                }
            }
        }
        return ret;
    }
    public void dfs(char[][] grid, int row, int col, int x, int y){
    
        grid[x][y] = '2';

        for(int i = 0; i < 4; i++){
            int newX = x + nextPostition[i][0];
            int newY = y + nextPostition[i][1];

            if(newX >= row || newX < 0 || newY >= col || newY < 0){
                continue;
            }
            //将值改为2表示该坐标已经遍历过
            if(grid[newX][newY] == '2'){
                continue;
            }
            if(grid[newX][newY] == '1'){
                dfs(grid, row, col, newX, newY);   
            }
        }
    }
}